package com.sunshine.lnuplus.view

import android.app.Activity
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.TypedValue
import android.view.LayoutInflater
import androidx.appcompat.widget.AppCompatEditText
import androidx.preference.CheckBoxPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SeekBarPreference
import com.google.android.material.textfield.TextInputLayout
import com.sunshine.lnuplus.R
import com.sunshine.lnuplus.callback.TimetableSettingCallBack
import com.sunshine.lnuplus.model.InitData
import com.sunshine.lnuplus.model.WidgetData
import com.sunshine.lnuplus.utils.TagHelper
import es.dmoral.toasty.Toasty
import kotlinx.android.synthetic.main.dialog_pick_color.view.*

class WidgetSettingView : PreferenceFragmentCompat(), Preference.OnPreferenceChangeListener,
    Preference.OnPreferenceClickListener {

    private lateinit var callback: TimetableSettingCallBack
    private lateinit var sp: SharedPreferences
    private lateinit var edit: SharedPreferences.Editor

    fun init(callback: TimetableSettingCallBack){
        this.callback = callback
    }
    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        setPreferencesFromResource(R.xml.setting_widget, rootKey)
        sp = context?.getSharedPreferences("com.sunshine.lnuplus_preferences", Context.MODE_PRIVATE)!!
        edit = sp.edit()

        preferenceManager.findPreference<SeekBarPreference>("widget_text_size")?.apply {
            onPreferenceChangeListener = this@WidgetSettingView
            summary = "${this.value}sp"
        }
        preferenceManager.findPreference<SeekBarPreference>("widget_height")?.apply {
            onPreferenceChangeListener = this@WidgetSettingView
            summary = "${this.value}dp"
        }
        preferenceManager.findPreference<SeekBarPreference>("widget_alpha")?.apply {
            onPreferenceChangeListener = this@WidgetSettingView
            summary = "${this.value.toFloat()/255*100}%"
        }
        preferenceManager.findPreference<SeekBarPreference>("widget_radius")?.apply {
            onPreferenceChangeListener = this@WidgetSettingView
            summary = "${this.value}"
        }
        preferenceManager.findPreference<SeekBarPreference>("widget_width_distance")?.apply {
            onPreferenceChangeListener = this@WidgetSettingView
            summary = "${this.value}dp"
        }
        preferenceManager.findPreference<SeekBarPreference>("widget_height_distance")?.apply {
            onPreferenceChangeListener = this@WidgetSettingView
            summary = "${this.value}dp"
        }
        preferenceManager.findPreference<SeekBarPreference>("widget_padding")?.apply {
            onPreferenceChangeListener = this@WidgetSettingView
            summary = "${this.value}dp"
        }
        preferenceManager.findPreference<SeekBarPreference>("widget_time_text_size")?.apply {
            onPreferenceChangeListener = this@WidgetSettingView
            summary = "${this.value}sp"
        }
        preferenceManager.findPreference<CheckBoxPreference>("widget_show_weekend")?.apply {
            onPreferenceChangeListener = this@WidgetSettingView
        }
        preferenceManager.findPreference<CheckBoxPreference>("widget_show_not_in_this_week")?.apply {
            onPreferenceChangeListener = this@WidgetSettingView
        }
        preferenceManager.findPreference<CheckBoxPreference>("widget_show_teacher")?.apply {
            onPreferenceChangeListener = this@WidgetSettingView
        }
        preferenceManager.findPreference<CheckBoxPreference>("widget_sunday_first")?.apply {
            onPreferenceChangeListener = this@WidgetSettingView
        }
        preferenceManager.findPreference<CheckBoxPreference>("widget_show_time")?.apply {
            onPreferenceChangeListener = this@WidgetSettingView
        }
        preferenceManager.findPreference<CheckBoxPreference>("widget_next_day")?.apply {
            onPreferenceChangeListener = this@WidgetSettingView
            preferenceManager.findPreference<Preference>("widget_next_day_time")?.isEnabled = this.isChecked
        }
        preferenceManager.findPreference<Preference>("widget_next_day_time")?.apply {
            onPreferenceClickListener = this@WidgetSettingView
            summary = "当前指定时间：${sp.getInt("widget_next_day_time", 21)}点"
        }
        preferenceManager.findPreference<Preference>("widget_text_color")?.apply {
            onPreferenceClickListener = this@WidgetSettingView
        }
        preferenceManager.findPreference<Preference>("widget_date_and_time_text_color")?.apply {
            onPreferenceClickListener = this@WidgetSettingView
        }
        preferenceManager.findPreference<Preference>("widget_date_color")?.apply {
            onPreferenceClickListener = this@WidgetSettingView
        }
    }

    override fun onPreferenceChange(preference: Preference?, newValue: Any?): Boolean {
        when(preference?.key){
            "widget_text_size" -> {
                preference.summary = "${newValue}sp"
                WidgetData.widgetStyle!!.textSize = newValue as Int
                callback.onChanged()
            }
            "widget_height" -> {
                preference.summary = "${newValue}dp"
                WidgetData.widgetStyle!!.height = newValue as Int
                if(newValue < 150) Toasty.info(context!!, "调节过小可能引起界面错乱，请自行判断").show()
                callback.onChanged()
            }
            "widget_alpha" -> {
                preference.summary = "${(newValue as Int).toFloat()/255*100}%"
                WidgetData.widgetStyle!!.alpha = newValue
                callback.onChanged()
            }
            "widget_radius" -> {
                preference.summary = "$newValue"
                WidgetData.widgetStyle!!.round = newValue as Int
                callback.onChanged()
            }
            "widget_width_distance" -> {
                preference.summary = "${newValue}dp"
                WidgetData.widgetStyle!!.widthDistant = newValue as Int
                callback.onChanged()
            }
            "widget_height_distance" -> {
                preference.summary = "${newValue}dp"
                WidgetData.widgetStyle!!.heightDistant = newValue as Int
                callback.onChanged()
                val dateHeight = TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP,
                    50f,
                    context!!.resources.displayMetrics
                ).toInt()
                val widgetHeight = (1920-dateHeight - (sp.getInt("every_day_count", 5) - 1)*newValue)/sp.getInt("count", 5)
                if(sp.getInt("widget_height", (1920-dateHeight - 4*10)/5) > widgetHeight){
                    edit.putInt("widget_height", widgetHeight)
                    preferenceManager.findPreference<SeekBarPreference>("widget_height")!!.max = widgetHeight
                }
            }
            "widget_padding" -> {
                preference.summary = "${newValue}dp"
                WidgetData.widgetStyle!!.padding = newValue as Int
                callback.onChanged()
            }
            "widget_time_text_size" -> {
                preference.summary = "${newValue}sp"
                WidgetData.widgetStyle!!.timeTextSize = newValue as Int
                callback.onChanged()
            }
            "widget_show_weekend" -> {
                WidgetData.widgetStyle!!.showWeekend = newValue as Boolean
                callback.onChanged()
            }
            "widget_show_not_in_this_week" -> {
                WidgetData.widgetStyle!!.showNotInThisWeek = newValue as Boolean
                callback.onChanged()
            }
            "widget_show_teacher" -> {
                WidgetData.widgetStyle!!.showTeacher = newValue as Boolean
                callback.onChanged()
            }
            "widget_show_time" -> {
                WidgetData.widgetStyle!!.showTime = newValue as Boolean
                callback.onChanged()
            }
            "widget_sunday_first" -> {
                WidgetData.widgetStyle!!.sundayFirst = newValue as Boolean
                callback.onChanged()
            }
            "widget_next_day" -> {
                val boolean = newValue as Boolean
                preferenceManager.findPreference<Preference>("widget_next_day_time")?.isEnabled = boolean
                callback.onChanged()
            }
        }
        return true
    }

    override fun onPreferenceClick(preference: Preference?): Boolean {
        when(preference?.key){
            "widget_text_color" -> {
                val view = LayoutInflater.from(context).inflate(R.layout.dialog_pick_color, null, false)
                var tempColor = ""
                val pickColor = DialogWithView.newInstance(
                    view,
                    "请选择课程格子文字颜色",
                    false,
                    DialogInterface.OnClickListener { _, _ ->
                        val edit = context!!.getSharedPreferences("com.sunshine.lnuplus_preferences", Context.MODE_PRIVATE).edit()
                        edit.apply{
                            putString("widget_text_color", tempColor)
                            apply()
                        }
                        WidgetData.widgetStyle!!.textColor = tempColor
                        callback.onChanged()
                    },
                    null)
                pickColor.show(childFragmentManager, "pickColor")
                view.color_pick_view.setOnColorChangeListener {
                    tempColor = String.format("%08x",it)
                    tempColor = "#" + tempColor.substring(2, tempColor.length)
                }
            }

            "widget_date_and_time_text_color" -> {
                val view = LayoutInflater.from(context).inflate(R.layout.dialog_pick_color, null, false)
                var tempColor = ""
                val pickColor = DialogWithView.newInstance(
                    view,
                    "请选择时间和日期文字颜色",
                    false,
                    DialogInterface.OnClickListener { _, _ ->
                        val edit = context!!.getSharedPreferences("com.sunshine.lnuplus_preferences", Context.MODE_PRIVATE).edit()
                        edit.apply{
                            putString("widget_date_and_time_text_color", tempColor)
                            apply()
                        }
                        WidgetData.widgetStyle!!.dateAndTimeTextColor = tempColor
                        callback.onChanged()
                    },
                    null)
                pickColor.show(childFragmentManager, "pickColor")
                view.color_pick_view.setOnColorChangeListener {
                    tempColor = String.format("%08x",it)
                    tempColor = "#" + tempColor.substring(2, tempColor.length)
                }
            }
            "widget_date_color" -> {
                val view = LayoutInflater.from(context).inflate(R.layout.dialog_pick_color, null, false)
                var tempColor = ""
                val pickColor = DialogWithView.newInstance(
                    view,
                    "请选择日期栏“今日”指示按钮颜色",
                    false,
                    DialogInterface.OnClickListener { _, _ ->
                        val edit = context!!.getSharedPreferences("com.sunshine.lnuplus_preferences", Context.MODE_PRIVATE).edit()
                        edit.apply{
                            putString("widget_date_color", tempColor)
                            apply()
                        }
                        WidgetData.widgetStyle!!.dateColor = tempColor
                        callback.onChanged()
                    },
                    null)
                pickColor.show(childFragmentManager, "pickColor")
                view.color_pick_view.setOnColorChangeListener {
                    tempColor = String.format("%08x",it)
                    tempColor = "#" + tempColor.substring(2, tempColor.length)
                }
            }
            "widget_next_day_time" -> {
                val view = LayoutInflater.from(context).inflate(R.layout.dialog_calender_time, null, false)
                view.findViewById<TextInputLayout>(R.id.til_count_down_time).hint = "输入范围0~23"
                val dialog = DialogWithView.newInstance(
                    view,
                    "请输入指定时间",
                    false,
                    DialogInterface.OnClickListener { _, _ ->
                        try {
                            val time = view.findViewById<AppCompatEditText>(R.id.edit_calender_time).text.toString().toInt()
                            if(time < 0 || time > 23){
                                Toasty.error(context!!, "输入有问题呀~").show()
                            }else{
                                val preference = preferenceManager.findPreference<Preference>("widget_next_day_time")
                                preference?.summary = "当前指定时间：${time}点"
                                edit.putInt("widget_next_day_time", time)
                                edit.apply()
                            }
                        }catch (e: Exception){
                            Toasty.error(context!!, "输入有问题呀~").show()
                        }

                    },
                    null)
                dialog.show(childFragmentManager, "")
            }
        }
        return true
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == TagHelper.TIMETABLEVIEW){
            if(resultCode == Activity.RESULT_OK){
                callback.onChanged()
            }
        }
    }

}